home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / minix / libsrc~1.z / libsrc~1 / popen.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-12-28  |  1.4 KB  |  68 lines

  1. #include "lib.h"
  2. #include <stdio.h>
  3. #include <signal.h>
  4. #include <sys/wait.h>
  5.  
  6. static int pids[20];
  7.  
  8. FILE *
  9. popen(command, type)
  10. _CONST char *command, *type;
  11. {
  12.     int piped[2];
  13.     int Xtype = *type == 'r' ? 0 : *type == 'w' ? 1 : 2;
  14.     int pid;
  15. #ifndef __STDC__    /* for __STDC__ pick up proto from <std.h> */
  16.     extern FILE *fdopen();
  17. #endif
  18.  
  19.     if (Xtype == 2 ||
  20.         pipe(piped) < 0 ||
  21.         (pid = fork()) < 0) return 0;
  22.     
  23.     if (pid == 0) {
  24.         /* child */
  25.         register int *p;
  26.  
  27.         for (p = pids; p < &pids[20]; p++) {
  28.             if (*p) close(p - pids);
  29.         }
  30.         close(piped[Xtype]);
  31.         dup2(piped[!Xtype], !Xtype);
  32.         close(piped[!Xtype]);
  33.         execl("/bin/sh", "sh", "-c", command, (char *) 0);
  34.         exit(127);    /* like system() ??? */
  35.     }
  36.  
  37.     pids[piped[Xtype]] = pid;
  38.     close(piped[!Xtype]);
  39.     return fdopen(piped[Xtype], type);
  40. }
  41.  
  42. int pclose(iop)
  43.     FILE *iop;
  44. {
  45.     int fd = fileno(iop);
  46.     int status, wret;
  47. #ifdef __STDC__
  48.     void (*intsave)() = signal(SIGINT, SIG_IGN);
  49.     void (*quitsave)() = signal(SIGQUIT, SIG_IGN);
  50.     void (*hupsave)() = signal(SIGHUP, SIG_IGN);
  51. #else
  52.     int (*intsave)() = signal(SIGINT, SIG_IGN);
  53.     int (*quitsave)() = signal(SIGQUIT, SIG_IGN);
  54.     int (*hupsave)() = signal(SIGHUP, SIG_IGN);
  55. #endif
  56.  
  57.     fclose(iop);
  58.     while ((wret = wait(&status)) != -1) {
  59.         if (wret == pids[fd]) break;
  60.     }
  61.     if (wret == -1) status = -1;
  62.     signal(SIGINT, intsave);
  63.     signal(SIGQUIT, quitsave);
  64.     signal(SIGHUP, hupsave);
  65.     pids[fd] = 0;
  66.     return status;
  67. }
  68.